package com.wechat.wechat.aspect;

import antlr.StringUtils;
import com.sun.javafx.binding.StringFormatter;
import com.wechat.wechat.constant.CookieConstant;
import com.wechat.wechat.constant.RedisConstant;
import com.wechat.wechat.enums.ResultEnum;
import com.wechat.wechat.exception.SellException;
import com.wechat.wechat.exception.SellerAuthorizeException;
import com.wechat.wechat.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 验证用户是否登陆的切面
 * @author NN
 * @2020/2/28 21:38
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.wechat.wechat.controller.Seller*.*(..))"+
    "&& !execution(public * com.wechat.wechat.controller.SellerUserController.*(..))")
    public void verify(){}

    /**
     * 在用户访问管理系统前处理
     */
    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes attributes=
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();

        //查询cookie token值是redis的key
        Cookie cookie= CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie==null)
        {
            log.warn("【登陆校验】cookie中找不到token");
            throw new SellerAuthorizeException();
        }
        //去redis中查询
        String tokenValue=redisTemplate.opsForValue()
                .get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if(tokenValue==null)
        {
            log.warn("【登陆校验】redis中找不到token");
            throw new SellerAuthorizeException();
        }
    }
}
